import json
import sys
import logging
import httpx
from intelli_port.commons.config import load_settings


class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = {
            "ts": self.formatTime(record, datefmt="%Y-%m-%dT%H:%M:%SZ"),
            "level": record.levelname,
            "service": getattr(record, "service", "api"),
            "agent": getattr(record, "agent", ""),
            "terminal": getattr(record, "terminal", ""),
            "corr_id": getattr(record, "corr_id", ""),
            "req_id": getattr(record, "req_id", ""),
            "event": record.msg,
        }
        return json.dumps(payload, ensure_ascii=False)


def json_logger(name: str = "intelli-port") -> logging.Logger:
    logger = logging.getLogger(name)
    if not logger.handlers:
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(JsonFormatter())
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
    return logger


def emit_to_elastic(event: dict) -> None:
    s = load_settings()
    if not s.elastic_endpoint:
        return
    url = s.elastic_endpoint.rstrip("/") + "/intelli-port-logs/_doc"
    try:
        with httpx.Client(timeout=1.0) as client:
            client.post(url, json=event)
    except Exception as e:
        logger = json_logger()
        logger.info("elastic.emit.error", extra={"service": "api", "event": str(e)})